<?php

namespace org\copperforest\oak\http\exceptions;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class HTTPHelper
{

    static protected $_output_charset;
    static protected $_output_type;

    static function getHeaderCharset()
    {
        //cuando se ejecuta debería haberse enviado el header con el charset, con lo cual deberbía poder obtenerlo
        $headers = headers_list();

        foreach ( $headers as $h ) {
            $h = explode( ':', $h, 1 );

            if ( strtoupper( $h[ 0 ] ) == 'CONTENT-TYPE' ) {
                $h = explode( ';', $h[ 1 ] );

                self::$_output_type = $h[ 0 ];

                $h = explode( '=', $h[ 1 ] );

                if ( strtoupper( $h[ 0 ] ) == 'CHARSET' )
                        self::$_output_charset = $h[ 1 ];
            }
        }
    }

    //Aqui se pueden definir HTTPExceptions
    /**
     * Envía al buffer de salida el contenido del fichero indicado
     * @param string $file
     * @param boolean $attach
     * @param int $expires
     * @return boolean
     */
    final static function output( $file, $attach = false, $expires = null )
    {
        //do something on download abort/finish
        //register_shutdown_function( 'function_name'  );
        if ( !file_exists( $file ) ) exit();

        $size = filesize( $file );
        $name = rawurlencode( basename( $file ) );

        @ob_end_clean(); /// decrease cpu usage extreme

        if ( $attach )
                header( 'Content-Disposition: attachment; filename="' . $name . '"' );
        else header( 'Content-Disposition: inline; filename="' . $name . '"' );

        if ( $expires === null ) {
            header( 'Expires: ' . gmdate( 'D, d M Y H:i:s',
                            $_SERVER[ 'REQUEST_TIME' ] + 7 * 24 * 60 * 60 ) . ' GMT' ); //una semana tienen
        } else {
            header( 'Cache-control: private, Max-Age=' . ($expires - $_SERVER[ 'REQUEST_TIME' ]) );
            header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', $expires ) . ' GMT' );
        }

        header( 'Accept-Ranges: bytes' );
        header( 'Cache-control: private' );
        header( 'Pragma: private' );

        $first_byte = 0;
        $last_byte = $size - 1;

        /////  multipart-download and resume-download
        //check if http_range is sent by browser (or download manager)
        if ( isset( $_SERVER[ 'HTTP_RANGE' ] ) ) {
            if ( preg_match( '/^bytes\s*=\s*(\d+)-(\d*)$/',
                            $_SERVER[ 'HTTP_RANGE' ], $matches ) ) {

                $first_byte = ( int ) $matches[ 0 ];
                if ( !empty( $matches[ 1 ] ) )
                        $last_byte = ( int ) $matches[ 1 ];

                header( 'HTTP/1.1 206 Partial Content' );
            }
        }

        $left_size = ($last_byte - $first_byte) + 1;
        header( 'Content-Range: bytes ' . $first_byte . '-' . $last_byte . '/' . $size );
        header( 'Content-Length: ' . $left_size );

        //open the file
        $fp = fopen( $file, 'rb' );
        //seek to start of missing part
        fseek( $fp, $first_byte );

        //start buffered download
        while ( !feof( $fp ) ) {
            //reset time limit for big files
            set_time_limit( 30 );
            print(fread( $fp, 1024 * 8 ) ); //bloques de 8Kb
            flush();
            ob_flush();
        }
        fclose( $fp );

        return true;
    }

}